package com.mytool.domain;

import lombok.Data;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.apache.commons.text.CaseUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class TableDomain {
    private String tableName;
    private String domainObjectName;
    private String fieldName;
    private String tableComment;

    private List<ColumnDomain> columns;

    public TableDomain() {

    }

    public TableDomain(CreateTable createTable) {
        this.tableName = createTable.getTable().getName().replaceAll("`","");
        this.domainObjectName = CaseUtils.toCamelCase(tableName.replace("t_","").replace("tbl_",""), false, '_');
        this.domainObjectName = StringUtils.capitalize(this.domainObjectName);
        this.fieldName = StringUtils.uncapitalize(this.domainObjectName);
        this.tableComment = getTableComment(createTable);
        this.columns = getColumns(createTable);
    }

    private String getTableComment(CreateTable createTable) {
        List<String> tableOptionsStrings = createTable.getTableOptionsStrings();
        Map<String,String> options = new HashMap<>();
        for(int i = 0; i < tableOptionsStrings.size();) {
            if(!ObjectUtils.nullSafeEquals("=", tableOptionsStrings.get(i + 1))) {
                i++;
                continue;
            }
            String key = tableOptionsStrings.get(i);
            String val = tableOptionsStrings.get((i + 2));
            i += 3;
            options.put(key,val);
        }
        return options.get("COMMENT");
    }

    private List<ColumnDomain> getColumns(CreateTable createTable) {
        List<ColumnDomain> list = new ArrayList<>();
        createTable.getColumnDefinitions().stream().forEach(it -> {
            ColumnDomain columnDomain = new ColumnDomain();
            columnDomain.setColumnName(it.getColumnName());
            columnDomain.setColumnType(it.getColDataType().getDataType());
            columnDomain.setJavaType(ColumnDomain.TYPE_MAPPING.get(columnDomain.getColumnType().toUpperCase()));
            List<String> columnSpecs = it.getColumnSpecs();
            if(null != columnSpecs && columnSpecs.size() > 1) {
                int len = columnSpecs.size();
                if("COMMENT".equalsIgnoreCase(columnSpecs.get(len - 2))) {
                    columnDomain.setColumnComment(columnSpecs.get(len - 1).replaceAll("`", ""));
                }
            }
            list.add(columnDomain);
        });
        return list;
    }
}
